import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:ichinesereader/constants.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/controller/user.dart';
import 'package:ichinesereader/pages/individual/individualHomeHiLevel.dart';
import 'package:ichinesereader/utils/log.dart';
import 'package:ichinesereader/widgets/layouts/appdrawerIndividual.dart';
import 'package:ichinesereader/widgets/layouts/customAppBar.dart';

class IndividualHome extends StatefulWidget {
  static const String routeName = '/individual/home';

  @override
  _IndividualHomeState createState() => _IndividualHomeState();
}

class _IndividualHomeState extends State<IndividualHome> {
  final UserController _userController = Get.find();
  var box = Hive.box('appconfig');
  bool isStudent = false;
  bool isLowLevel = false;

  @override
  void initState() {
    super.initState();

    bool isDark = box.get('theme', defaultValue: 0) == 1;
    int locale = box.get('locale', defaultValue: 0);

    Future.delayed(Duration(milliseconds: 200), () {
      _userController.getProfile();

      if (isDark) {
        Get.changeThemeMode(ThemeMode.dark);
      } else {
        Get.changeThemeMode(ThemeMode.light);
      }

      if (locale == 0) {
        Get.updateLocale(Locale('en', 'US'));
      }
      if (locale == 1) {
        Get.updateLocale(Locale('zh', 'CN'));
      }
      if (locale == 2) {
        Get.updateLocale(Locale('zhHant', 'TW'));
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Log.debug('start building individual home page');

    final isSmallScreen =
        MediaQuery.of(context).size.width < Constants.DefinedScreenSmallSize;

    return Scaffold(
      backgroundColor: Colors.transparent,
      appBar: isSmallScreen ? CustomAppBar(title: 'Home'.tr) : null,
      drawer: isSmallScreen ? IndividualAppDrawer() : null,
      body: Obx(() {
        if (_userController.profile.value.userName != null) {
          var level = int.tryParse(_userController.profile.value.level
                  .toString()
                  .replaceAll('level', '')) ??
              1;
          if (level > 0 && level < 6) isLowLevel = true;

          box.put('UserLevel', level.toString());
          return IndividualHomeHiLevel();
        } else {
          return Text('');
        }
      }),
    );
  }
}
